package com.cloudinnov.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudinnov.utils.CommonUtils;

/**
 * @ahtuor libo
 * @email boli@cloudinnov.com
 * @日期 2017年5月8日 下午6:24:37
 */
@ServerEndpoint("/boardControlSolutionDialogue")
public class BoardControlSolutionDialogueWebsocket {
	private static Logger LOG = LoggerFactory.getLogger(BoardControlSolutionDialogueWebsocket.class);
	public static final String SPLIT1 = ":";
	private String random;
	private static int onlineCount = 0;
	// 用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
	public static ConcurrentMap<String, BoardControlSolutionDialogueWebsocket> webSocketMap = new ConcurrentHashMap<String, BoardControlSolutionDialogueWebsocket>();
	// 用来发送数据
	private Session session;

	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
		this.random = CommonUtils.getUUID();
		webSocketMap.put(random, this);
		// 连接人数加1
		addOnlineCount();
		LOG.debug("设备状态推送开始连接:" + random);
	}
	@OnMessage
	public void onMessage(String message) {
	}
	@OnError
	public void onError(Throwable throwable, Session session) {
		LOG.error("设备状态推送异常:" + random);
	}
	@OnClose
	public void onClose(Session session) {
		webSocketMap.remove(random);
		subOnlineCount(); // 在线数减1
		LOG.debug("设备状态推送连接关闭:" + random);
	}
	public synchronized void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
	}
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}
	public static synchronized void addOnlineCount() {
		BoardControlSolutionDialogueWebsocket.onlineCount++;
	}
	public static synchronized void subOnlineCount() {
		BoardControlSolutionDialogueWebsocket.onlineCount--;
	}
}
